package com.ipet.app.ui.common;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.afollestad.materialdialogs.MaterialDialog;
import com.ipet.app.R;
import com.ipet.app.api.BaseCallBack;
import com.ipet.app.api.RequestManager;
import com.ipet.app.bean.apiRequestBean.CreateTopicRequest;
import com.ipet.app.bean.apiRequestBean.SearchTopicRequest;
import com.ipet.app.bean.apiResponseBean.CreateTopicResponse;
import com.ipet.app.bean.apiResponseBean.SearchTopicResponse;
import com.ipet.app.ui.base.SwipeBackActivity;
import com.ipet.app.ui.widget.TagView;
import com.ipet.app.ui.widget.helper.Tag.OnTagClickListener;
import com.ipet.app.ui.widget.helper.Tag.OnTagDeleteListener;
import com.ipet.app.ui.widget.helper.Tag.Tag;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jindongping on 16/3/14.
 */
public class MultiTagViewSelectorActivity extends SwipeBackActivity {

    private CoordinatorLayout coordinatorLayout;

    private TagView tagGroup1, tagGroup2;
    private ArrayList<Tag> localTag;

    /**
     * 选择结果，返回为标签id集合
     */
    public static final String EXTRA_RESULT = "select_result";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_tag_selector);
        //不弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        initToolbar();
        initDate();
        initTagGroup();
        initSearchView();
    }


    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("选择标签");
        toolbar.setNavigationIcon(R.drawable.btn_back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_CANCELED);
                finish();
            }
        });
    }

    private void initDate() {
        localTag = new ArrayList<>();
        final MaterialDialog dialog = showLoadingDialogNoTitle("加载中...");
        RequestManager.getApi().searchTopic(new SearchTopicRequest("")).enqueue(new Callback<SearchTopicResponse>() {
            @Override
            public void onResponse(Call<SearchTopicResponse> call, Response<SearchTopicResponse> response) {
                dialog.dismiss();
                if (response.body().isSucess()) {
                    List<SearchTopicResponse.Topic> topics = response.body().getTopicList();
                    for (SearchTopicResponse.Topic topic : topics) {
                        Tag tag = new Tag(topic.getTopic_name());
                        tag.id = Integer.parseInt(topic.getTopic_id());
                        tag.radius = 10;
                        tag.isDeletable = false;
                        localTag.add(tag);
                    }
                    tagGroup2.addTags(localTag);
                } else {
                    snackErr(coordinatorLayout, response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<SearchTopicResponse> call, Throwable t) {
                dialog.dismiss();
                snackErr(coordinatorLayout, "加载失败,请检查网络");
            }
        });

//        for (int i = 0; i < 10; i++) {
//            Tag tag = new Tag("tag" + i);
//            tag.radius = 10;
//            tag.isDeletable = false;
//            localTag.add(tag);
//        }
    }

    private void initSearchView() {
        EditText et = (EditText) findViewById(R.id.edit_text);
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                final String searchStr = s.toString();
                if (searchStr.equals("")) {
                    tagGroup2.addTags(localTag);
                    return;
                }
                initAddTagButton(searchStr);
                boolean tagIsInlocal = false;
                //将每次找到的结果放入该tag
                final ArrayList<Tag> tags = new ArrayList<>();
                for (int i = 0; i < localTag.size(); i++) {
                    //从已缓存的tag中找
                    if (localTag.get(i).text.startsWith(searchStr)) {
                        tags.add(localTag.get(i));
                        tagIsInlocal = true;
//                        KLog.v("jdp","从本地找到了");
                    }
                }
                if (!tagIsInlocal) {
                    //从网络中找
                    RequestManager.getApi().searchTopic(new SearchTopicRequest(searchStr)).enqueue(new BaseCallBack<SearchTopicResponse>() {
                        @Override
                        public void onRequestSuccess(SearchTopicResponse response) {
//                            KLog.v("jdp","访问网络成功");
                            if (response.isSucess()) {
                                List<SearchTopicResponse.Topic> topics = response.getTopicList();
                                for (SearchTopicResponse.Topic topic : topics) {
                                    Tag tag = new Tag(topic.getTopic_name());
                                    tag.id = Integer.parseInt(topic.getTopic_id());
                                    tag.radius = 10;
                                    tag.isDeletable = false;
//                                    KLog.v("jdp", "找到了");
                                    //加入到缓存
                                    localTag.add(tag);
                                    tagGroup2.addTag(tag);
                                }
                            }

                        }
                    });

                }
                tagGroup2.addTags(tags);
//                KLog.v("jdp", "重新设置标签");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


    }

    private void initAddTagButton(final String searchStr) {
        final Button btnAddTag = (Button) findViewById(R.id.btn_add_tag);
        btnAddTag.setVisibility(View.VISIBLE);
        btnAddTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MaterialDialog dialog = showLoadingDialogNoTitle("增加标签中...");
                RequestManager.getApi().createTopic(new CreateTopicRequest(searchStr)).enqueue(new BaseCallBack<CreateTopicResponse>(coordinatorLayout, dialog) {
                    @Override
                    public void onRequestSuccess(CreateTopicResponse response) {
                        snackShow(coordinatorLayout, "添加" + searchStr + "标签成功");
                        Tag tag = new Tag(searchStr);
                        tag.id = Integer.parseInt(response.getTopicId());
                        tag.radius = 10;
                        tag.isDeletable = true;
                        tagGroup1.addTag(tag);
                        //copy一份到本地 再查找就不会进行网络请求了
                        Tag tagCopy = new Tag(searchStr);
                        tagCopy.id = Integer.parseInt(response.getTopicId());
                        tagCopy.radius = 10;
                        tagCopy.isDeletable = false;
                        localTag.add(tagCopy);
                    }
                });
            }
        });
    }

    private void initTagGroup() {
        tagGroup1 = (TagView) findViewById(R.id.tagView1);
        tagGroup2 = (TagView) findViewById(R.id.tagView2);
        tagGroup2.addTags(localTag);

        tagGroup1.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onTagClick(Tag tag, int position) {
                snackShow(coordinatorLayout, tag.text + position);
            }
        });

        tagGroup1.setOnTagDeleteListener(new OnTagDeleteListener() {

            @Override
            public void onTagDeleted(final TagView view, final Tag tag, final int position) {
                view.remove(position);
                tag.isDeletable = false;
                tagGroup2.addTag(tag);
            }
        });

        tagGroup2.setOnTagClickListener(new OnTagClickListener() {
            @Override
            public void onTagClick(Tag tag, int position) {
                localTag.remove(tag);
                tagGroup2.remove(position);
                tag.isDeletable = true;
                tagGroup1.addTag(tag);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.confrim_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_confirm) {
            Intent data = new Intent();
            List<Tag> tags = tagGroup1.getTags();
            ArrayList<Integer> chooseTagsId = new ArrayList<>();
            for (Tag tag : tags) {
                chooseTagsId.add(tag.id);
            }
            data.putIntegerArrayListExtra(EXTRA_RESULT, chooseTagsId);
            setResult(RESULT_OK, data);
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}
